import lodash from 'lodash';
import moment from 'moment';
import { jvmData } from '../services/jvm-controller';
import { fmtDateTime } from '../utils/fmt'

export default {
  namespace: 'JmvsModel',

  state: {
    queryParam: {
      index: undefined,
      // 开始时间 - 6天前
      startTime: moment().subtract(15, 'minutes'),
      // 时间长度 YYYY-MM-DD HH:mm:ss
      longTime: '15m',
    },

    longTimeList: [
      { value: '1m', label: '1分钟' },
      { value: '5m', label: '5分钟' },
      { value: '15m', label: '15分钟' },
      { value: '30m', label: '30分钟' },
      { value: '1H', label: '1小时' },
      { value: '3H', label: '3小时' },
      { value: '5H', label: '5小时' },
      { value: '10H', label: '10小时' },
    ],

    data: [],
  },

  effects: {
    *findData({ payload }, { select, call, put }) {
      const { currentSysName } = yield select(state => state.GlobalEnumModel);
      let { queryParam } = yield select(state => state.JmvsModel);
      queryParam = { ...queryParam, index: currentSysName, ...payload };
      // 处理 queryParam
      const longTimeUnit = queryParam.longTime.charAt(queryParam.longTime.length - 1);
      const longTimeNum = lodash.toNumber(queryParam.longTime.substring(0, queryParam.longTime.length - 1));
      const max = moment(queryParam.startTime).add(longTimeNum, longTimeUnit === 'm' ? 'minutes' : 'hours');
      const resultData = yield call(jvmData, { index: queryParam.index, max: fmtDateTime(max), min: fmtDateTime(queryParam.startTime) });
      if (!resultData) return;
      // 保存数据
      yield put({ type: 'save', payload: { queryParam, data: resultData.hits.hits } });
      yield put({ type: 'GlobalEnumModel/save', payload: { currentSysName: queryParam.index } });
    },
  },

  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};
